#include "stdafx.h"
#include "resource.h"

#include "NameTblViewerDlg.h"

#include "../nes/nes.h"

#define REFRESH_NAMETBL_TIMER 10

BOOL
CNameTblViewerDlg::PreTranslateMessage(MSG* pMsg)
{
  return IsDialogMessage(pMsg);
}

LRESULT
CNameTblViewerDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/,
                                LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
  CenterWindow(GetParent());
  SetTimer(REFRESH_NAMETBL_TIMER, 10);
  return TRUE;
}

void
CNameTblViewerDlg::Draw()
{
  if (g_NES && !g_NES->Running()) {
    return;
  }

  u16* image = g_NES->GetNameTblImage();

  int width = NAME_TBL_W*2;
  int height = NAME_TBL_H*2;
  BITMAPINFO bi = {
    // 1                      2      3        4  5   6  7  8  9  10 11
    sizeof(BITMAPINFOHEADER), width, -height, 1, 16, 0, 0, 0, 0, 0, 0
  };
  RECT rc;
  ::GetClientRect(m_hWnd, &rc);
  HDC hDC = ::GetDC(m_hWnd);
  ::StretchDIBits(hDC, 0, 0, rc.right - rc.left, rc.bottom - rc.top, 0, 0,
                  width, height, image, &bi, DIB_RGB_COLORS, SRCCOPY);
  ::ReleaseDC(m_hWnd, hDC);
}

LRESULT
CNameTblViewerDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/,
                           BOOL& /*bHandled*/)
{
  switch (wParam)
  {
    case REFRESH_NAMETBL_TIMER:
      Draw();
      break;
  }
  return TRUE;
}

LRESULT
CNameTblViewerDlg::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/,
                           LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
  m_IsShow = false;
  ShowWindow(false);
  return FALSE;
}

BOOL
CNameTblViewerDlg::ShowHideMe()
{
  m_IsShow = !m_IsShow;
  ShowWindow(m_IsShow);
  if (m_IsShow) {
    SetTimer(REFRESH_NAMETBL_TIMER, 30);
  } else {
    KillTimer(REFRESH_NAMETBL_TIMER);
  }
  return TRUE;
}
